<template>
  <div class="user">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      </el-col>
    </el-row>

   <el-row :gutter="10">
      <el-col :span="4">
        <!-- 给组件绑定原生事件的话，需要一个.native的修饰符 -->
        <el-input placeholder="请输入账号" class="search-input" v-model="query" @keydown.native.enter="initList"  size="medium">
          <el-button slot="append" icon="el-icon-search" @click="initList"  size="medium" ></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="success" plain @click="addUser" size="medium">添加用户</el-button>
      </el-col>
    </el-row>

    <el-table
      class="margin-20"
      v-loading="loading"
      :data="userList"
      border
      style="width: 100%">
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="UserName"
        label="账户"
        width="180">
      </el-table-column>
      <el-table-column
        prop="UserCName"
        label="用户名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="RecordDatetime"
        label="注册时间"
        width="280">
      </el-table-column>
      <el-table-column label="用户状态" >
        <template slot-scope="scope">
          <el-switch v-model="scope.row.RecordState" @change="changeUserState(scope.row)"  :active-value= 1
    :inactive-value= 0></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- <template >slot-scope="scope" -->
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-delete"  @click="showDeleteDialog(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[10,20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

     <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible" width="20%">
      <el-form :model="addUserForm" label-width="80px" :rules="rules" ref="addUserForm" size="medium" >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addUserForm.userName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input v-model="addUserForm.userPwd" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="userPwdComfirm">
          <el-input v-model="addUserForm.userPwdComfirm" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userCName">
          <el-input v-model="addUserForm.userCName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="recordState">
          <el-switch v-model="addUserForm.recordState" active-text="启用" inactive-text="停用" :active-value= 1
    :inactive-value= 0>
          </el-switch>
        </el-form-item>
        <el-form-item label="域用户" prop="isDomain">
          <el-switch v-model="addUserForm.isDomain" active-text="是" inactive-text="否" :active-value= 1
    :inactive-value= 0>
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="addUserSubmit('addUserForm')" size="medium">确 定</el-button>
      </div>
    </el-dialog>

     <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible" width="20%">
      <el-form :model="editUserForm" label-width="80px" :rules="editrules" ref="editUserForm" size="medium">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editUserForm.userName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input v-model="editUserForm.userPwd" auto-complete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="userPwdComfirm">
          <el-input v-model="editUserForm.userPwdComfirm" auto-complete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userCName">
          <el-input v-model="editUserForm.userCName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="recordState">
          <el-switch v-model="editUserForm.recordState" active-text="启用" inactive-text="停用" :active-value= 1
    :inactive-value= 0>
          </el-switch>
        </el-form-item>
        <el-form-item label="域用户" prop="isDomain">
          <el-switch v-model="editUserForm.isDomain" active-text="是" inactive-text="否" :active-value= 1
    :inactive-value= 0>
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit('editUserForm')" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, addUser, getUserById, checkUserName, editUser, deleteUser } from '@/api'
export default {
  data () {
    var validateUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名'))
      }
      setTimeout(() => {
        checkUserName({ params: { txt: value, id: this.userid } }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              callback(new Error('用户名已经存在'))
            } else {
              callback()
            }
          } else {
            callback(new Error('用户名验证失败'))
          }
        })
      }, 500)
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.addUserForm.userPwd !== '') {
          this.$refs.addUserForm.validateField('userPwdComfirm')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addUserForm.userPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    var validateEditPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.editUserForm.userPwd !== '') {
          this.$refs.editUserForm.validateField('userPwdComfirm')
        }
        callback()
      }
    }
    var validateEditPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.editUserForm.userPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      userList: [],
      userid: 0,
      query: '',
      total: 0,
      pagesize: 10,
      pagenum: 1,
      addDialogFormVisible: false,
      addUserForm: {
        userName: '',
        userPwd: '',
        userPwdComfirm: '',
        userCName: '',
        isDomain: 0,
        recordState: 1,
        recordPerson: '',
        recordDatetime: ''
      },
      editDialogFormVisible: false,
      editUserForm: {
        ID: '',
        userName: '',
        userPwd: '',
        userPwdComfirm: '',
        userCName: '',
        isDomain: 0,
        recordState: 1,
        recordPerson: '',
        recordDatetime: ''
      },
      // 添加用户的表单验证
      rules: {
        userName: [
          { required: true, validator: validateUserName, trigger: 'blur' }
        ],
        userPwd: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        userPwdComfirm: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        userCName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      },
      // 编辑用户表单验证
      editrules: {
        userName: [
          { required: true, validator: validateUserName, trigger: 'blur' }
        ],
        userPwd: [
          { required: true, validator: validateEditPass, trigger: 'blur' }
        ],
        userPwdComfirm: [
          { required: true, validator: validateEditPass2, trigger: 'blur' }
        ],
        userCName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.initList()
  },
  methods: {
    handleSizeChange (val) {
      this.pagesize = val
      this.initList()
    },
    handleCurrentChange (val) {
      this.pagenum = val
      this.initList()
    },
    // 初始化表格数据
    initList () {
      this.loading = true
      getUserList({ params: { STxtUserName: this.query, page: this.pagenum, rows: this.pagesize } }).then(res => {
        // let datajson = JSON.parse(res.data)
        this.userList = res.data.rows
        this.total = res.data.total
        this.loading = false
      })
    },
    // 改变用户状态
    changeUserState (row) {
      editUser(row).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '修改用户状态成功'
          })
          this.initList()
        }
      })
    },
    addUser () {
      this.addDialogFormVisible = true
      this.resetForm('addUserForm')
    },
    // 新增用户
    addUserSubmit (formName) {
      this.$refs[formName].validate(valide => {
        if (valide) {
          // 执行添加用户方法
          addUser(this.addUserForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '创建用户成功'
              })
              this.addDialogFormVisible = false
              this.initList()
            }
          })
        }
      })
    },
    // 显示编辑用户对话框
    showEditDialog (row) {
      this.editDialogFormVisible = true
      this.resetForm('editUserForm')
      getUserById(row.ID).then(res => {
        if (res.code === 200) {
          this.userid = res.data.ID
          this.editUserForm.ID = res.data.ID
          this.editUserForm.userName = res.data.UserName
          this.editUserForm.userPwd = res.data.UserPwd
          this.editUserForm.userPwdComfirm = res.data.UserPwd
          this.editUserForm.userCName = res.data.UserCName
        }
      })
    },
    // 编辑用户提交
    editUserSubmit (formName) {
      this.$refs[formName].validate(valide => {
        if (valide) {
          editUser(this.editUserForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '编辑成功'
              })
              this.editDialogFormVisible = false
              this.initList()
            }
          })
        }
      })
    },
    // 显示删除对话框
    showDeleteDialog (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除用户操作
        deleteUser(row.ID).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetForm (formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.user {
  .margin-20 {
    margin: 20px 0;
  }
  .page {
    padding: 5px 0;
    background-color: #D3DCE6;
  }
}
</style>
